package service

import (
	"bytes"
	"crypto/sha256"
	"crypto/tls"
	"encoding/base64"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/google/uuid"
	jsoniter "github.com/json-iterator/go"
	"zhonghui/console/warehouse/envx"
	"zhonghui/console/warehouse/logx"
)

func ProductUrl() map[string]string {
	if envx.InProd() {
		return map[string]string{
			"p1": "https://channelh5.pubmi.cn/h5/jhbao2023Detail?channel=ZT23021701",
			"p2": "https://channelh5.pubmi.cn/h5/jhbao2024Detail?mp=",
			"p3": "https://channelh5.pubmi.cn/h5/jhbaoDetail2024?mp=",
			"p4": "https://channelh5.pubmi.cn/h5/jhbao2025Detail?mp=",
		}
	}

	return map[string]string{
		"p1": "https://uat-channelh5.pubmi.cn/h5/jhbao2023Detail?channel=ZT23021701",
		"p2": "https://uat-channelh5.pubmi.cn/h5/jhbao2023Detail?channel=ZT23021701",
		"p3": "https://channelh5.pubmi.cn/h5/jhbaoDetail2024?mp=",
		"p4": "https://uat-channelh5.pubmi.cn/h5/jhbao2025Detail?mp=",
	}
}

// WSSE_HEADER_FORMAT 无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
const WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\""

// AUTH_HEADER_VALUE 无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
const AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\""

func SendZhonghuiSms(phone string, param []string, templateId string) error {
	// 必填,请参考"开发准备"获取如下数据,替换为实际值
	apiAddress := "https://smsapi.cn-south-1.myhuaweicloud.com:443/sms/batchSendSms/v1" // APP接入地址(在控制台"应用管理"页面获取)+接口访问URI
	appKey := "38ks524eHJdtL6n39ECSfj93Z91w"                                            // APP_Key
	appSecret := "iGIvyFXHI2P8QatV9GtedS5m119l"                                         // APP_Secret
	sender := "8822120739512"                                                           // 国内短信签名通道号或国际/港澳台短信通道号
	sender = "8824032124111"                                                            // todo 通知短信渠道
	if templateId == "" {
		return errors.New("invalid template id")
	}

	// 条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
	// 国际/港澳台短信不用关注该参数
	signature := "众惠相互" // 签名名称

	// 必填,全局号码格式(包含国家码),示例:+86151****6789,多个号码之间用英文逗号分隔
	receiver := "+86" + phone // 短信接收人号码

	// 选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
	statusCallBack := ""

	/*
	 * 选填,使用无变量模板时请赋空值 string templateParas = "";
	 * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
	 * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
	 * 模板中的每个变量都必须赋值，且取值不能为空
	 * 查看更多模板和变量规范:产品介绍>模板和变量规范
	 */
	j, _ := jsoniter.MarshalToString(param)
	templateParas := j // 模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。
	logx.Zap().Infow("短信发送模板变量", "var", param)

	body := buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature)
	headers := make(map[string]string)
	headers["Content-Type"] = "application/x-www-form-urlencoded"
	headers["Authorization"] = AUTH_HEADER_VALUE
	headers["X-WSSE"] = buildWsseHeader(appKey, appSecret)
	res, err := post(apiAddress, []byte(body), headers)
	if err != nil {
		logx.Zap().Errorw("短信发送失败", "err", err)
		return err
	}
	logx.Zap().Infow("短信发送结果", "res", res)

	// 判断逻辑成功
	resp := struct {
		Code        string `json:"code"`
		Description string `json:"description"`
	}{}
	_ = jsoniter.UnmarshalFromString(res, &resp)

	if resp.Code != "000000" {
		return errors.New("短信发送失败:" + resp.Description)
	}

	return nil
}

/**
* sender,receiver,templateId不能为空 */
func buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature string) string {
	param := "from=" + url.QueryEscape(sender) + "&to=" + url.QueryEscape(receiver) + "&templateId=" +
		url.QueryEscape(templateId)
	if templateParas != "" {
		param += "&templateParas=" + url.QueryEscape(templateParas)
	}
	if statusCallBack != "" {
		param += "&statusCallback=" + url.QueryEscape(statusCallBack)
	}
	if signature != "" {
		param += "&signature=" + url.QueryEscape(signature)
	}
	return param
}
func post(url string, param []byte, headers map[string]string) (string, error) {
	fmt.Println(string(param))
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	client := &http.Client{Transport: tr}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(param))
	if err != nil {
		return "", err
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(body), nil
}
func buildWsseHeader(appKey, appSecret string) string {
	var cTime = time.Now().Format("2006-01-02T15:04:05Z")
	var nonce = uuid.New().String()
	nonce = strings.ReplaceAll(nonce, "-", "")
	h := sha256.New()
	h.Write([]byte(nonce + cTime + appSecret))
	passwordDigestBase64Str := base64.StdEncoding.EncodeToString(h.Sum(nil))
	return fmt.Sprintf(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, cTime)
}
